/* ---省市区级联组件----
*/
import { getProvCityArea } from '../api/extra';
import cookie from 'react-cookies';


let AreaData;
export async function areaData() {
    let post_data = {
        'auth_token':cookie.load('station_console_setting_web_login').auth_token,
        
    }
    await getProvCityArea(post_data).then(res => {
        AreaData = res.data.prov_city_area;
        sessionStorage.setItem('AreaData', JSON.stringify(AreaData));
        setAreaData();
    })
}

export async function setAreaData() {
    let AreaDataArr = [];
    let prov_arr = AreaData[86];
    for (let i in prov_arr) {
        // console.log(i) //编码
        // console.log(prov_arr[i]) //字符
        AreaDataArr.push({
            value: prov_arr[i],
            label: prov_arr[i],
            code: i
        })
    }
    for (let j in AreaData) {
        AreaDataArr.forEach(arr => {
            if (j === arr.code) {
                let city_arr = [];
                for (let n in AreaData[j]) {
                    city_arr.push({
                        value: AreaData[j][n],
                        label: AreaData[j][n],
                        code: n
                    })
                }
                arr.children = city_arr
            }
        })
    }
    for (let m in AreaData) {
        AreaDataArr.forEach(arr => {
            arr.children.forEach(arr => {
                let area_arr = [];
                if (m === arr.code) {
                    for (let l in AreaData[m]) {
                        area_arr.push({
                            value: AreaData[m][l],
                            label: AreaData[m][l],
                            code: l
                        })
                    }
                    arr.children = area_arr
                }
            })
        })
    }
    AreaData = AreaDataArr
}

export async function data() {
    if (sessionStorage.getItem('AreaData')){
        console.log('取本地地址库数据')
        AreaData = JSON.parse(sessionStorage.getItem('AreaData'));
        await setAreaData();
    }else{
        console.log('取线上地址库数据')
        await areaData();
    }
    if (!AreaData) {
        AreaData = []
        alert('地址库接口数据异常！')
        return;
    }
    return AreaData;
}
export default {
    data,
    areaData
}